package com.jstyle.jclife.activity;

import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.LinearSnapHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;

import com.jstyle.jclife.R;
import com.jstyle.jclife.adapter.TeamperdataAdapter;
import com.jstyle.jclife.adapter.TeamperformanceAdapter;
import com.jstyle.jclife.model.Teamperformance;
import com.jstyle.jclife.utils.ScreenUtils;
import com.jstyle.jclife.utils.Utils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 团队战绩
 */
public class TeamperformanceActivity extends BaseActivity {
    @BindView(R.id.rvRc)
    RecyclerView rvRc;
    @BindView(R.id.teamdataRecyclerView)
    RecyclerView teamdataRecyclerView;
    TeamperdataAdapter teamperdataAdapter;
    TeamperformanceAdapter teamperformanceAdapter;
    List<Teamperformance> myDatas = new ArrayList<>();
    private LinearLayoutManager mLinearLayoutManager;
    private LinearLayoutManager mLinearLayoutManagertwo;
    private Handler handler = new Handler();
    /**
     * 记录当前选中的位置,默认位置是0
     */
    private int nowPosition = 1;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_teamperformance);
        ButterKnife.bind(this);
        mLinearLayoutManager = new LinearLayoutManager(this);
        mLinearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        new LinearSnapHelper().attachToRecyclerView(rvRc);
        rvRc.setLayoutManager(mLinearLayoutManager);
        teamperformanceAdapter = new TeamperformanceAdapter(TeamperformanceActivity.this);
        rvRc.setAdapter(teamperformanceAdapter);
        //添加假数据
        myDatas.clear();
        Teamperformance bb = new Teamperformance();
        bb.setCount(30);
        bb.setTeampnmae("友宏\\n战队");
        bb.setRanking(2);
        bb.setTargetNumber(100);
        bb.setAverageDuration("ss:ss:ss");
        bb.setMeanDistance("100公里");
        bb.setAverageStepFrequency("100步/分钟");
        bb.setAverageStepNumber("100步");
        bb.setFastestSpeedDistribution("01’23”");
        bb.setAverageSpeedDistribution("22’25”");

        Teamperformance cc = new Teamperformance();
        cc.setCount(20);
        cc.setTeampnmae("西乡\\n战队");
        cc.setRanking(1);
        cc.setTargetNumber(90);
        cc.setAverageDuration("ss:ss:ss");
        cc.setMeanDistance("100公里");
        cc.setAverageStepFrequency("100步/分钟");
        cc.setAverageStepNumber("100步");
        cc.setFastestSpeedDistribution("01’23”");
        cc.setAverageSpeedDistribution("22’25”");

        Teamperformance dd = new Teamperformance();
        dd.setTargetNumber(80);
        dd.setCount(20);
        dd.setTeampnmae("某某\\n战队");
        dd.setRanking(3);
        dd.setAverageDuration("ss:ss:ss");
        dd.setMeanDistance("100公里");
        dd.setAverageStepFrequency("100步/分钟");
        dd.setAverageStepNumber("100步");
        dd.setFastestSpeedDistribution("01’23”");
        dd.setAverageSpeedDistribution("22’25”");

        Teamperformance ff = new Teamperformance();
        ff.setRanking(4);
        ff.setCount(20);
        ff.setTeampnmae("hahha\\n战队");
        ff.setAverageDuration("ss:ss:ss");
        ff.setMeanDistance("100公里");
        ff.setAverageStepFrequency("100步/分钟");
        ff.setAverageStepNumber("100步");
        ff.setFastestSpeedDistribution("01’23”");
        ff.setAverageSpeedDistribution("22’25”");
        myDatas.add(bb);
        myDatas.add(dd);
        myDatas.add(ff);
        myDatas.add(cc);

        myDatas = DataRearrangement(myDatas);
        //注意前三条数据需要从服务器拿过来后排序下，按照 2-1-3排列
        teamperformanceAdapter.setdta(myDatas);
        mLinearLayoutManagertwo = new LinearLayoutManager(this);
        mLinearLayoutManagertwo.setOrientation(LinearLayoutManager.VERTICAL);
        teamdataRecyclerView.setLayoutManager(mLinearLayoutManagertwo);
        teamperdataAdapter = new TeamperdataAdapter(this);
        teamdataRecyclerView.setAdapter(teamperdataAdapter);
        teamperdataAdapter.SettingData(MyDATA(myDatas, nowPosition));


        rvRc.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == 0) {
                    if (myDatas.size() >= 2 && mLinearLayoutManager.findFirstCompletelyVisibleItemPosition() + 1 != myDatas.size() - 1) {
                        nowPosition = mLinearLayoutManager.findFirstCompletelyVisibleItemPosition() + 1;
                        teamperdataAdapter.SettingData(MyDATA(myDatas, nowPosition));
                    }
                }
            }

            @Override
            public void onScrolled(@NonNull final RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                final int childCount = mLinearLayoutManager.getChildCount();
                if (childCount == 1) {
                    final RelativeLayout childCounttwo = recyclerView.getChildAt(0).findViewById(R.id.teamRt);
                    ViewGroup.LayoutParams params = childCounttwo.getLayoutParams();
                    params.height = ScreenUtils.dip2px(TeamperformanceActivity.this, 150f);// 控件的高强制设成20
                    params.width =ScreenUtils.dip2px(TeamperformanceActivity.this, 110f);
                    childCounttwo.setLayoutParams(params);
                    final RelativeLayout childCo = recyclerView.getChildAt(0).findViewById(R.id.teamtileRt);
                    ViewGroup.LayoutParams para = childCo.getLayoutParams();
                    para.width = recyclerView.getMeasuredWidth();
                    childCo.setLayoutParams(para);
                } else {
                    for (int i = 0; i < childCount; i++) {
                        if (i != mLinearLayoutManager.findFirstCompletelyVisibleItemPosition() + 1) {
                            RelativeLayout child = recyclerView.getChildAt(i).findViewById(R.id.teamRt);
                            ViewGroup.LayoutParams params = child.getLayoutParams();
                            params.height = ScreenUtils.dip2px(TeamperformanceActivity.this, 136f);// 控件的高强制设成20
                            child.setLayoutParams(params);
                            child.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
                            child.setVerticalGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
                        } else {
                            RelativeLayout childCounttwo = recyclerView.getChildAt(mLinearLayoutManager.findFirstCompletelyVisibleItemPosition() + 1).findViewById(R.id.teamRt);
                            ViewGroup.LayoutParams params = childCounttwo.getLayoutParams();
                            params.height = ScreenUtils.dip2px(TeamperformanceActivity.this, 150f);// 控件的高强制设成20
                            childCounttwo.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
                            childCounttwo.setVerticalGravity(Gravity.CENTER_HORIZONTAL | Gravity.BOTTOM);
                            childCounttwo.setLayoutParams(params);
                        }
                    }
                }
            }
        });
        //Item的点击回调监听
        teamperformanceAdapter.setOnItemClickListener(new TeamperformanceAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(final View v, final int position) {
                if (nowPosition != position && position != teamperformanceAdapter.getItemCount() && 0 != position) {
                    //使点击到的条目滚动到中间
                    nowPosition = position;
                    Log.e("dffff", nowPosition + "");
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            int vWidth = v.getWidth();
                            Rect rect = new Rect();
                            rvRc.getGlobalVisibleRect(rect);
                            int reWidth = rect.right - rect.left - vWidth; //除掉点击View的宽度，剩下整个屏幕的宽度
                            final int firstPosition = mLinearLayoutManager.findFirstVisibleItemPosition();
                            int left = rvRc.getChildAt(position - firstPosition).getLeft();//从左边到点击的Item的位置距离
                            int half = reWidth / 2;//半个屏幕的宽度
                            int moveDis = left - half;//向中间移动的距离
                            rvRc.smoothScrollBy(moveDis, 0);
                        }
                    });
                }
            }
        });

    }


    /**
     * 第一次排列数据
     *
     * @param list
     * @return
     */
    private List DataRearrangement(List<Teamperformance> list) {
        if (list.size() <= 1) {
            return list;
        } else {
            return Utils.swap2(Soretlist(list), 0, 1);
        }
    }


    private List<Teamperformance> Soretlist(List<Teamperformance> devices) {
        //使用冒泡排序算法
        for (int i = 0; i < devices.size() - 1; i++) {
            for (int j = 0; j < devices.size() - 1 - i; j++) {
                if (devices.get(j).getRanking() > devices.get(j + 1).getRanking()) {
                    Teamperformance devive = devices.get(j);
                    devices.set(j, devices.get(j + 1));
                    devices.set(j + 1, devive);
                }
            }
        }
        return devices;
    }

    /**
     * 返回三条数据显示（前提是有三条数据）
     *
     * @return
     */
    private List<Teamperformance> MyDATA(List<Teamperformance> myDatas, int position) {
        if (myDatas.size() >= 3) {
            List<Teamperformance> teamperformance = new ArrayList<>();
            teamperformance.add(myDatas.get(position - 1));
            teamperformance.add(myDatas.get(position));
            teamperformance.add(myDatas.get(position + 1));
            return teamperformance;
        } else {
            return myDatas;
        }
    }


    @OnClick({R.id.iv_back})
    public void onViewClicked(View view) {
        if (Utils.isFastClick()) { return; }
        switch (view.getId()) {
            case R.id.iv_back:
                finish();
                break;

        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (null != handler) {
            handler.removeCallbacksAndMessages(null);
        }

    }
}
